package com.cy.pj.common.aspect;

import com.cy.pj.common.annotation.RequiredCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect //定义切面
@Component
public class SysCacheAspect {
    private final Map<Object,Object> cache = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCatch(){}

    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClear(){}

    /**
     * 业务正常结束后才执行此方法
     */
    @AfterReturning("doClear()")
    public void doAfterReturning(JoinPoint jp) throws NoSuchMethodException {
        //1.先获取切入点方法的签名
        MethodSignature ms = (MethodSignature) jp.getSignature();
//        Method method = ms.getMethod();//代理方式不同,结果也不同
        //1.1通过反射获取目标方法对象
        Class<?> targetCls = jp.getTarget().getClass();
        Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        //2.获取目标方法对象上的注解
        RequiredCache requiredCache = targetMethod.getAnnotation(RequiredCache.class);
        //3.再去获取目标方法对象上的注解的key
        Object key = requiredCache.key();
        //4.根据目标的key来移除相应的缓存
        cache.remove(key);
//        cache.clear();
    }

    @Around("doCatch()")
    public Object doAround(ProceedingJoinPoint jp) throws Throwable {
        /**
         * 获取拦截到的切入点方法上的注解中的key,通过这个key再存入到 cache 中
         */
        //1.先获取切入点方法的签名
        MethodSignature ms = (MethodSignature) jp.getSignature();
//        Method method = ms.getMethod();//代理方式不同,结果也不同
        //1.1通过反射获取目标方法对象
        Class<?> targetCls = jp.getTarget().getClass();
        Method targetMethod = targetCls.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        //2.获取目标方法对象上的注解
        RequiredCache requiredCache = targetMethod.getAnnotation(RequiredCache.class);
        //3.再去获取目标方法对象上的注解的key
        Object key = requiredCache.key();

        //先从缓存中取数据,如果没有拿到,再去请求数据库
        Object data = cache.get(key);
        if(data != null){
            System.out.println("Get Data from Cache");
            return data;
        }
        
        //如果cache中没有数据,再去数据库中拿数据
        data = jp.proceed();
        System.out.println("Get Data from Mysql");
        System.out.println("Put Data to Cache");
        //数据库中拿到了数据后再放一份到cache中
        cache.put(key, data);
        return data;
    }
}
